<!-- eslint-disable vue/multi-word-component-names -->
<!-- eslint-disable-next-line vue/valid-template-root -->
<script setup>
import {
  reactive,
  ref,
  onMounted,
  watch
} from 'vue'
import Edictor from '@/components/Editor/edictor.vue'
import { useI18n } from 'vue-i18n'
import { filterArticleItem } from '@/utils/api/article.js'
import axios from 'axios'
const { t } = useI18n()

import { getNoteList } from '@/utils/api/note.js'
import { base64ToString } from '@/utils/note'

import { useNoteTag } from '@/store/noteTag.js'

import Note from './Items/Note.vue'
import Article from './Items/Article.vue'

const target_tag = useNoteTag()
const _data = reactive({
  active: null,
  nav_list: []
})

const isLogin = ref(false)

const isLoading = ref(true)
const page = reactive({
  Number: 1,
  Size: 5
})

const data = ref([
  // {
  //   id: 1,
  //   type: 'note',
  //   content:
  //     // '<p>#📝日常 /note/NVNad https://www.bing.com 年前还兴致勃勃地折腾些代码，年后回来就懒下来了，也不知道在忙什么。</p>',
  //     '<p>#📝日常&nbsp;/note/NVNad&nbsp;https://www.bing.com&nbsp;年前还兴致勃勃地折腾些代码，年后回来就懒下来了，也不知道在忙什么。</p>',
  //   createTime: 1720513371445,
  //   updateTime: 1720513371445,
  //   tags: ['📝日常'],
  //   category: [],
  //   mark: {
  //     browser: {
  //       name: 'Microsoft Edge',
  //       version: '126.0.0.0'
  //     },
  //     os: {
  //       name: 'Windows',
  //       version: 'NT 10.0',
  //       versionName: '10'
  //     },
  //     platform: {
  //       type: 'desktop'
  //     },
  //     engine: {
  //       name: 'Blink'
  //     }
  //   },
  //   images: []
  // }
])

const addNotes = async (params = {}) => {
  let notes = await getNoteList({
    noteClassify: target_tag.get(),
    status: 1,
    pageNum: page.Number,
    pageSize: page.Size,
    ...params
  })
  // console.log(data.value.length, notes.total)

  isLoading.value =
    data.value.length != notes.total
      ? true
      : false

  if (!isLoading.value) return

  if (
    data.value.length &&
    notes.rows.length &&
    data.value[data.value.length - 1].id ==
      notes.rows[notes.rows.length - 1].id
  )
    return

  notes.rows.forEach((i) => {
    i.type = 'note'
    i.tags = JSON.parse(i.noteClassify)
    i.content = base64ToString(i.noteContext)
    i.mark = JSON.parse(i.noteFrom)
    data.value.push(i)
  })
}

const addArticles = async () => {
  let articles = await filterArticleItem()
  articles = {
    rows: articles.data.rows,
    total: articles.data.total
  }
  articles.rows.map((o) => {
    o.type = 'article'
    data.value.push(o)
  })

  isLoading.value =
    data.value.length != articles.total
      ? true
      : false

  if (!isLoading.value) return
}

const addItems = async () => {
  switch (_data.active.type) {
    case 'note':
      await addNotes(_data.active.params)
      break
    case 'article':
      await addArticles()
      break
    default:
      break
  }
}

window.addEventListener('scroll', async () => {
  const documentHeight =
    document.documentElement.scrollHeight
  const viewportHeight = window.innerHeight
  const scrollTop =
    window.pageYOffset ||
    document.documentElement.scrollTop
  if (
    scrollTop + viewportHeight >=
      documentHeight - 10 &&
    isLoading.value != false
  ) {
    page.Number++
    await addItems()
  }
})

watch(
  () => _data.active,
  async () => {
    page.Number = 1
    page.Size = 5
    data.value = []
    await addItems()
  }
)

watch(
  () => target_tag.get(),
  async () => {
    page.Number = 1
    page.Size = 5
    data.value = []
    _data.active = _data.nav_list[0]
    await addItems()
  }
)

const getLoginStatus = async () => {
  let res = await axios.get('/prod-api/getInfo', {
    headers: {
      Authorization: localStorage.getItem('token')
    }
  })
  return res.data.code
}

onMounted(async () => {
  let code = await getLoginStatus()

  isLogin.value = code == 200 ? true : false

  isLogin.value
    ? (_data.nav_list = [
        // { name: t('common.All'), path: '/notes' },
        { name: t('common.Notes'), type: 'note' },
        {
          name: t('common.Articles'),
          type: 'article'
        },
        {
          name: '私密',
          type: 'note',
          params: { status: 0 }
        }
      ])
    : (_data.nav_list = [
        // { name: t('common.All'), path: '/notes' },
        { name: t('common.Notes'), type: 'note' },
        {
          name: t('common.Articles'),
          type: 'article'
        }
      ])

  _data.active = _data.nav_list[0]

  await addItems()
})
</script>
<template>
  <main class="notes-core">
    <Edictor v-if="isLogin" />

    <!-- NoteNav选项开始 -->
    <div class="notes-tabbar sticky bg-blur">
      <ul class="tab">
        <template
          v-for="(item, index) in _data.nav_list"
          :key="index"
        >
          <li
            class="tab-item"
            :class="{
              active: _data.active == item
            }"
          >
            <a
              href="javascript: void(0);"
              @click="_data.active = item"
              >{{ item.name }}</a
            >
          </li>
        </template>
      </ul>
    </div>

    <!-- NoteNav选项结束 -->

    <!-- 列表开始 -->
    <div class="notes-list">
      <template
        v-for="(item, index) in data"
        :key="index"
      >
        <template v-if="item.type == 'note'">
          <Note :item="item" />
        </template>
        <template
          v-else-if="item.type == 'article'"
        >
          <Article :item="item"></Article>
        </template>
        <template v-else> </template>
      </template>

      <div class="loading" v-if="isLoading"></div>
      <div
        class="text-center load-next-comments"
        v-else
      >
        <span>没有更多了</span>
      </div>
    </div>
    <!-- 列表结束 -->
  </main>
</template>

<style lang="scss" scoped></style>
